package gem.database;

import java.sql.SQLException;

public class DBConnection
{
	private static int maxValidation = 60;
	private static int loginTimeout = 5;
	private static String jdbcDriver = "com.mysql.jdbc.Driver";
	private static String jdbcUrl = "jdbc:mysql://localhost/gem?user=root&password=test&characterSetResults=UTF-8&characterEncoding=UTF8&useUnicode=true";
	private static java.sql.Connection connection = null;	
	//====================================================//
	public static java.sql.Connection getConnection()
	{
		if( connection == null )
		{
			connect();
		}
		return connection;
	}
	//====================================================//
	public static boolean connect( String url )
	{
		jdbcUrl = url;
		return ( reconnect() );
	}
	//====================================================//
	private static boolean connect()
	{
		try
		{
			java.sql.DriverManager.setLoginTimeout( loginTimeout );
			java.sql.Driver driver = (java.sql.Driver) Class.forName(jdbcDriver).newInstance();
			connection = java.sql.DriverManager.getConnection( jdbcUrl );
			
			if( connection == null)
			{
				// TODO messagebox
				return false;
			}
			return true;
		}
		catch(java.sql.SQLException e )
		{
			// TODO messagebox;
			e.printStackTrace();
			return false;
		}
		catch( java.lang.Exception e )
		{
			e.printStackTrace();
			return false;
		}
	}
	//====================================================//
	private static boolean disconnect()
	{
		try
		{
			if( connection != null )
			{
				connection.close();
			}
			return true;
		}
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		finally
		{
			connection = null;
		}		
	}
	//====================================================//
	public static boolean reconnect()
	{
		return ( disconnect() && connect() );
	}
	//====================================================//
	public static boolean isConnected()
	{
		boolean connected = false;
		try
        {
			//stavljamo 60 sekundi kao maksimalno vreme za povezivanje.
            connected = connection.isValid( maxValidation );           
        }
		catch (SQLException ex)
		{
			ex.printStackTrace();
            //java.util.logging.Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }

		return connected;
	}
	//====================================================//
	//====================================================//
	//====================================================//

}
